package educrypt.database.dao;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Observable;

import educrypt.database.Connector;

public class TextTypeDAO extends Observable {

	/* Singleton */
	private TextTypeDAO() {
	}

	public static TextTypeDAO getInstance() {
		return SingletonHolder.instance;
	}

	private static class SingletonHolder {
		public static final TextTypeDAO instance = new TextTypeDAO();
	}
	/* END Singleton */

	public List<String> findAll() {
		String sqlFindAllTextTypes = "SELECT * FROM TextType";
		List<String> allTextTypes = new ArrayList<String>();
		try {
			Connection conn = Connector.getConnection();
			Statement st = conn.createStatement();
			ResultSet rs = st.executeQuery(sqlFindAllTextTypes);
			while (rs.next()) {
				allTextTypes.add(rs.getString("name"));
			}
			rs.close();
			st.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return allTextTypes;
	}

	public boolean exists(String textType) {
		String sqlExistsTextType = "SELECT COUNT(*) from TextType WHERE name=?";
		boolean exists = false;
		try {
			Connection conn = Connector.getConnection();
			PreparedStatement ps = conn.prepareStatement(sqlExistsTextType);
			ps.setString(1, textType);
			ResultSet rs = ps.executeQuery();
			if (rs.next()) {
				exists = rs.getInt(1) > 0;
			}
			rs.close();
			ps.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return exists;
	}

	public void create(String textType) {
		if (!exists(textType)) {
			String sqlCreateTextType = "INSERT INTO TextType (name) VALUES (?)";
			try {
				Connection conn = Connector.getConnection();
				PreparedStatement ps = conn.prepareStatement(sqlCreateTextType);
				ps.setString(1, textType);
				ps.executeUpdate();
				ps.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			this.notifyObservers();
		}
	}

	public void delete(String name) {
		// All tables related to the alphabet are deleted too
		String sqlDeleteAlphabet = "DELETE FROM TextType WHERE name='" + name
				+ "'";
		try {
			Connection conn = Connector.getConnection();
			Statement st = conn.createStatement();
			st.executeUpdate(sqlDeleteAlphabet);
			st.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		this.notifyObservers();
	}

	@Override
	public void notifyObservers() {
		this.setChanged();
		List<String> textTypes = this.findAll();
		this.notifyObservers(textTypes);
	}
}
